package com.save.rpgsavedecode.util;

import com.save.rpgsavedecode.entry.FileEntry;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class FileUtil {

    public static String getDirPath(String fullPath, String dirName) {
        fullPath += "\\";
        int i = fullPath.lastIndexOf("\\" + dirName + "\\");
        return fullPath.substring(0, i + dirName.length() + 1);
    }

    public static List<FileEntry> filter(List<FileEntry> list, String filterStrings) {
        return list.stream().filter(fileEntry -> {
            String[] split = filterStrings.split(",");
            for (int i = 0; i < split.length; i++) {
                split[i] = "^" + split[i] + "$";
            }
            String regexp = StringUtils.join(split, "|");
            return Pattern.compile(regexp).matcher(fileEntry.getOriginFile()).matches();
        }).collect(Collectors.toList());
    }

    public static byte[] readFile(String filePath) throws IOException {
        File file = new File(filePath);
        InputStream in = null;
        List<Byte> bytes = new ArrayList<>();
        try {
            System.out.println("以字节为单位读取文件内容，一次读一个字节：");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
//                System.out.write(tempbyte);
                bytes.add((byte) tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes1 = new byte[bytes.size()];
        for (int i = 0; i < bytes.size(); i++) {
            bytes1[i] = bytes.get(i).byteValue();
        }
        return bytes1;
    }

}
